import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;

public class SeconedServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        // 1. 获取请求基础信息
        String method = request.getMethod();
        String requestURL = request.getRequestURL().toString();
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();

        System.out.println("请求方法：" + method);
        System.out.println("完整请求URL：" + requestURL);
        System.out.println("请求资源URI：" + requestURI);
        System.out.println("上下文路径：" + contextPath);

        // 2. 获取请求头信息
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            System.out.println("Header Name: " + headerName + ", Value: " + headerValue);
        }

        String userAgent = request.getHeader("User-Agent");
        System.out.println("用户代理：" + userAgent);

        // 3. 获取客户端和服务器信息
        String host = request.getRemoteHost();
        String address = request.getRemoteAddr();
        int clientPort = request.getRemotePort();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String scheme = request.getScheme();

        System.out.println("客户端主机名：" + host);
        System.out.println("客户端IP地址：" + address);
        System.out.println("客户端端口：" + clientPort);
        System.out.println("服务器名称：" + serverName);
        System.out.println("服务器端口：" + serverPort);
        System.out.println("请求协议：" + scheme);

        // 4. 获取
        String param = request.getParameter("name");
        String[] hobbies = request.getParameterValues("hobby");
        String queryString = request.getQueryString();

        System.out.println("单个参数 name: " + (param != null ? param : "null"));
        System.out.println("多个参数 hobby: " + (hobbies != null ? Arrays.toString(hobbies) : "null"));
        System.out.println("查询字符串: " + (queryString != null ? queryString : "null"));

        // 5. 设置响应内容
        response.setContentType("text/html; charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);

        try (PrintWriter out = response.getWriter()) {
            out.println("<html><body>");
            out.println("<h1>请求处理成功</h1>");
            out.println("<p>客户端IP: " + address + "</p >");
            out.println("</body></html>");
        }
    }
}